package com.joinval.common.utils;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

//@Component
public class NextId {

    private AtomicLong seq = new AtomicLong();
    // 由于java Long最大19位，oracle正常显示是15位，因此这里获取的ID使用15位
    // 最大序列数(max_seq = 3)
    private int maxSeq = 3;

    private long getAtomicLong() {
        long atomic = this.seq.incrementAndGet();
        if (String.valueOf(atomic).length() > this.maxSeq) {
            //logger.info("超过最大的位数：{} reset from 0 start", maxSeq);
            this.seq.set(0L);
            return getAtomicLong();
        }
        return atomic;
    }

    private String getId() {
        SimpleDateFormat f = new SimpleDateFormat("yyMMddHHmmss");
        String prefix = f.format(new Date());
        long suffix = getAtomicLong();
        // 服务ID，分布式部署时候发挥作用(server_id = 0)
//		return prefix + 0 +
//		       String.format(new StringBuilder("%0").append(this.maxSeq).append("d").toString(),
//						     new Object[] { Long.valueOf(suffix) });
        return prefix + String.format(new StringBuilder("%0").append(this.maxSeq).append("d").toString(),
                new Object[]{Long.valueOf(suffix)})+new Random(5);
    }

    public Long getNextId(){
        return Long.valueOf(this.getId());
    }

    public Long getNextNewId(){
        return Long.valueOf(RandomUtils.nextInt());
    }

}
